package vitaliy.bondar.diamondcave;

import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import android.graphics.Point;

public class MovingGameObject extends GameObject
{
    public MovingGameObject( GameScene scene, final GameObject.Type type, final int pX, final int pY
    		, final ITiledTextureRegion pTiledTextureRegion, VertexBufferObjectManager vbom )
    {
        super( scene, type, pX, pY, pTiledTextureRegion, vbom);
    }

    public void move( Direction direction ) 
    {
    	this.m_isMoving = true;
    	
    	Point next = this.nextCell(direction);
    	m_scene.onObjectMoved( cellX(), cellY(), next.x, next.y );
    	this.setCell( next.x, next.y );
	}
    
    public void move(int x, int y) 
    {
        this.m_isMoving = true;
        
        m_scene.onObjectMoved(cellX(), cellY(), x, y);
        this.setCell(x, y);
    }
    
    public Point nextCell( Direction direction )
    {
    	switch( direction ) {
    	case RIGHT:
    	{
    		return new Point( cellX() + 1, cellY() );
    	}
    	case LEFT:
    	{
    		return new Point( cellX() - 1, cellY() );
    	}
    	case UP:
    	{
    		return new Point( cellX(), cellY() - 1 );
    	}
    	case DOWN:
    	{
    		return new Point( cellX(), cellY() + 1 );
    	}
    	default:
    		return null;
    	}
    }
    
    public boolean tryMove( Direction direction )
    {
    	if (this.m_isMoving) return false;
    	
    	Point next = nextCell( direction );
    	
    	GameObject obstacle = m_scene.findItemAtPosition( next.x, next.y );
    	
    	if( obstacle == null ) return true;
    	
    	if( obstacle instanceof MovingGameObject && !(obstacle instanceof Enemy))
		{
			MovingGameObject movable = ( MovingGameObject ) obstacle;
			
			if( movable.tryMove( direction ) )
			{
				movable.move(direction);
				
				return true;
			}
    	}
    	
    	return false;
    }
}
